﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using AutoShutdownDotNet.Models;
using AutoShutdownDotNet.Actions;
using AutoShutdownDotNet.Resources;

namespace AutoShutdownDotNet
{
    public partial class MainForm : Form
    {

        private List<Task> Tasks = new List<Task>();

        private Task QuickTask = new Task();

        private bool quickTaskStarted = false;

        private bool realyWantToExit = false;

        private bool isPasswordProtected = false;

        #region Properties

        public int SelectedTaskIndex
        {
            get
            {
                if(listTasks.SelectedItems.Count > 0)
                    return listTasks.SelectedIndices[0];
                return -1;
            }
        }

        public int SelectedTaskId
        {
            get
            {
                if (SelectedTaskIndex > -1)
                    return Tasks[SelectedTaskIndex].Id;
                return -1;
            }
        }

        public bool BusyOnWork { get; set; }

        #endregion

        #region Methods

        private void AddToList(Task task)
        {
            ListViewItem item = new ListViewItem(task.Title);
            item.Tag = task.Id;
            item.SubItems.Add(Task.ActionToString(task.Action));
            item.SubItems.Add(task.WhenToString());
            item.SubItems.Add(task.Time);
            item.SubItems.Add(task.Active ? "Enabled" : "Disabled");
            item.SubItems.Add(task.CreatedDate.ToShortDateString());
            item.SubItems.Add(task.LastModified.ToShortDateString());
            item.ImageIndex = ((int)task.Action) - 1;
            listTasks.Items.Add(item);
        }

        private void ShowTasks()
        {
            listTasks.Items.Clear();
            foreach (Task task in Tasks)
            {
                AddToList(task);
            }
        }

        private void CheckForUpcomeTasks()
        {
            DateTime now = DateTime.Now;
            
            if(QuickTask.Active && !BusyOnWork)
            {
                if(QuickTask.Hour == now.Hour && QuickTask.Minute == now.Minute)
                {
                    BusyOnWork = true;
                    if (QuickTask.AskBefore)
                    {
                        DoTaskForm doTaskForm = new DoTaskForm(QuickTask);
                        if (doTaskForm.ShowDialog() == DialogResult.Cancel)
                        {
                            QuickTask.Active = false;
                            BusyOnWork = false;
                        }
                    }
                    else
                    {
                        BusyOnWork = true;
                        DoAction doAction = new DoAction(QuickTask);
                        if (QuickTask.Action == AutoShutdownAction.ShowMessage)
                            new MessageForm(QuickTask.Title, QuickTask.Message).ShowDialog();
                        doAction.Do();
                        BusyOnWork = false;
                        QuickTask.Active = false;
                    }
                    BusyOnWork = false;
                    QuickTask.Active = false;
                    btnStartStop_Click(null, null);
                    return;
                }
            }

            foreach (Task task in Tasks)
            {
                if (task.Active && ((task.When.HasValue && task.When.Value == now) || task.When == null))
                {
                    if(task.Hour == now.Hour && task.Minute == now.Minute)
                    {
                        if (task.Recurrence == Recurrences.Everyday || Task.CompareDay(now.DayOfWeek,task.Recurrence)) 
                        {
                            BusyOnWork = true;
                            if (task.AskBefore)
                            {
                                DoTaskForm doTaskForm = new DoTaskForm(task);
                                if (doTaskForm.ShowDialog() == DialogResult.Cancel)
                                {
                                    task.Active = false;
                                    BusyOnWork = false;
                                }
                            }
                            else
                            {
                                BusyOnWork = true;
                                DoAction doAction = new DoAction(task);
                                if (task.Action == AutoShutdownAction.ShowMessage)
                                    new MessageForm(task.Title, task.Message).ShowDialog();
                                doAction.Do();
                                BusyOnWork = false;
                                task.Active = false;
                            }
                        }
                    }
                }
            }
            
        }

        private bool _firstTimeTimerStarts = true;
        private void SetTimer()
        {
            DateTime now = DateTime.Now;
            if (now.Second == 0)
                timer.Interval = 60000;
            else
                timer.Interval = 60000 - (now.Second*1000);
            ShowDateAndTime();
        }

        private void ShowDateAndTime()
        {
            lblDateAndTime.Text = DateTime.Now.ToShortDateString() + English.Status_TimeIs + DateTime.Now.Hour.ToString() + ":" +
                DateTime.Now.Minute.ToString();
        }

        #endregion

        public MainForm()
        {
            InitializeComponent();
            Setting setting = Setting.GetDefault();
            if(setting == null)
            {
                setting = new Setting();
                setting.FirstRun = true;
                setting.FirstRunDate = DateTime.Now;
                setting.LastRunDate = DateTime.Now;
                setting.StartWithWindows = false;
                Setting.Update(setting);
            }
            listTasks.SelectedIndices.Clear();
            numHour.Value = DateTime.Now.Hour;
            numMinute.Value = DateTime.Now.Minute;
            cboActions.SelectedIndex = 0;
            SetTimer();
            Tasks = Task.Select(null, null);
            ShowTasks();
            isPasswordProtected = setting.PasswordProtected;
            
        }

        private void listTasks_ItemActivate(object sender, EventArgs e)
        {
            if(SelectedTaskIndex > -1)
            {
                TaskForm taskForm = new TaskForm(Convert.ToInt32(SelectedTaskId));
                if(taskForm.ShowDialog() == DialogResult.OK)
                {
                    listTasks.SelectedItems[0].Text = taskForm.Title;
                    listTasks.SelectedItems[0].SubItems[1].Text = Task.ActionToString(taskForm.Action);
                    listTasks.SelectedItems[0].SubItems[2].Text = Task.WhenToString(taskForm.When, taskForm.Recurrence);
                    listTasks.SelectedItems[0].SubItems[3].Text = Task.TimeToString(taskForm.Hour,taskForm.Minute);
                    listTasks.SelectedItems[0].SubItems[4].Text = (taskForm.Active ? "Enabled" : "Disabled");
                    listTasks.SelectedItems[0].SubItems[6].Text = taskForm.ResultTask.LastModified.ToShortDateString();
                    listTasks.SelectedItems[0].ImageIndex = ((int) taskForm.Action) - 1;
                    Tasks[SelectedTaskIndex].Title = taskForm.Title;
                    Tasks[SelectedTaskIndex].Action = taskForm.Action;
                    Tasks[SelectedTaskIndex].Active = taskForm.Active;
                    Tasks[SelectedTaskIndex].AskBefore = taskForm.AskBeforeAnyAction;
                    Tasks[SelectedTaskIndex].Comment = taskForm.Comment;
                    Tasks[SelectedTaskIndex].FilePath = taskForm.FilePath;
                    Tasks[SelectedTaskIndex].Hour = taskForm.Hour;
                    Tasks[SelectedTaskIndex].Minute = taskForm.Minute;
                    Tasks[SelectedTaskIndex].Timer = taskForm.Timer;
                    Tasks[SelectedTaskIndex].When = taskForm.When;
                    Tasks[SelectedTaskIndex].LastModified = taskForm.ResultTask.LastModified;
                    Tasks[SelectedTaskIndex].Recurrence = taskForm.Recurrence;
                }
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Show();
            if (isPasswordProtected)
            {
                Enabled = notifyIcon.Visible = false;
                PasswordForm passwordForm = new PasswordForm();
                if (passwordForm.ShowDialog() == DialogResult.OK)
                    Enabled = notifyIcon.Visible = true;
                else
                {
                    realyWantToExit = true;
                    Close();
                }
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            ShowDateAndTime();
            if (_firstTimeTimerStarts)
                timer.Interval = 60000;
            if(!BusyOnWork)
                CheckForUpcomeTasks();
            _firstTimeTimerStarts = false;
        }

        private void NewTask(AutoShutdownAction action)
        {
            TaskForm taskForm = new TaskForm();
            taskForm.Action = action;
            if (taskForm.ShowDialog() == DialogResult.OK)
            {
                AddToList(taskForm.ResultTask);
                Tasks.Add(taskForm.ResultTask);
            }
        }

        private void mnuNewTask_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.PowerOff);
        }

        private void mnuNewAutoShutdown_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.PowerOff);
        }

        private void mnuNewAutoReboot_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.Reboot);
        }

        private void mnuNewAutoLogoff_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.Logoff);
        }

        private void mnuNewAutoStandby_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.Standby);
        }

        private void mnuNewAutoHibernate_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.Hibernate);
        }

        private void mnuNewAutoLock_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.Lock);
        }

        private void mnuNewAutoRun_Click(object sender, EventArgs e)
        {
            NewTask(AutoShutdownAction.RunApplication);
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(SelectedTaskIndex > -1)
            {
                if(MessageBox.Show(English.DeleteSelectedTasks,English.DeleteSelectedTasks_Title,
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (int i in listTasks.SelectedIndices)
                    {
                        Tasks[i].Delete();
                        Tasks.RemoveAt(i);
                        listTasks.Items.RemoveAt(i);
                    }
                }
            }
        }

        private void enableAlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach(ListViewItem item in listTasks.Items)
            {
                item.SubItems[4].Text = "Enabled";
                Tasks[item.Index].Active = true;
            }
        }

        private void disableAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listTasks.Items)
            {
                item.SubItems[4].Text = "Disabled";
                Tasks[item.Index].Active = false;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Do you realy want to exit?" + Environment.NewLine + 
                "Note: Your planned tasks will no longer executed if you exit.", "Exit",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                realyWantToExit = true;
                Application.Exit();
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !realyWantToExit;
            if(!realyWantToExit)
                Hide();
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            PasswordForm passwordForm = new PasswordForm();
            if (passwordForm.ShowDialog() == DialogResult.OK)
                Show();
        }

        private void listTasks_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool selected = (SelectedTaskIndex > -1);
            mnuOpen.Enabled = mnuDelete.Enabled = 
                btnDelete.Enabled = btnEditTask.Enabled = mnuEditDelete.Enabled = mnuEditDisable.Enabled 
             = mnuEditEnable.Enabled  = mnuEditOpen.Enabled = btnEnable.Enabled = btnDisable.Enabled = selected;
        }

        private void mnuEditEnable_Click(object sender, EventArgs e)
        {
            foreach (int i in listTasks.SelectedIndices)
            {
                listTasks.Items[i].SubItems[4].Text = "Enabled";
                Tasks[i].Active = true;
            }
        }

        private void mnuEditDisable_Click(object sender, EventArgs e)
        {
            foreach (int i in listTasks.SelectedIndices)
            {
                listTasks.Items[i].SubItems[4].Text = "Disabled";
                Tasks[i].Active = false;
            }
        }

        private void mnuEditSelectAll_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listTasks.Items)
            {
                item.Selected = true;
            }
        }

        private void mnuEditInvertSelect_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listTasks.Items)
            {
                item.Selected = !item.Selected;
            }
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Applications (*.exe)|*.exe|All files(*.*)|*.*";
            openDialog.CheckFileExists = true;
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openDialog.FileName;
            }
        }

        private void cboActions_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtFilePath.Enabled =
                btnOpenFile.Enabled = (cboActions.SelectedIndex == (int) AutoShutdownAction.RunApplication - 1);
            txtMessage.Enabled = (cboActions.SelectedIndex == (int)AutoShutdownAction.ShowMessage - 1);
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if(quickTaskStarted)
            {
                QuickTask.Active = false;
                btnStartStop.Text = "&Start";
                quickTaskStarted = false;
                numHour.Enabled = numMinute.Enabled = cboActions.Enabled =
                txtFilePath.Enabled = btnOpenFile.Enabled = txtMessage.Enabled =
                chkAsk.Enabled = numTimer.Enabled = true;
                txtFilePath.Enabled =
                btnOpenFile.Enabled = (cboActions.SelectedIndex == (int)AutoShutdownAction.RunApplication-1);
                txtMessage.Enabled = (cboActions.SelectedIndex == (int)AutoShutdownAction.ShowMessage -1);
                return;
            }

            

            if(cboActions.SelectedIndex+1 == (int)AutoShutdownAction.RunApplication)
                if (!File.Exists(txtFilePath.Text) || txtFilePath.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("The file you have selected to run actually not exists.", "Run Application",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    txtFilePath.Focus();
                    return;
                }
            if(cboActions.SelectedIndex+1 == (int)AutoShutdownAction.ShowMessage)
                if(txtMessage.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter something in 'Mesage' box.", "Show Message", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    txtMessage.Focus();
                    return;
                }
            if(QuickTask == null)
                QuickTask = new Task();
            QuickTask.Id = 0;
            QuickTask.Action = (AutoShutdownAction) cboActions.SelectedIndex+1;
            QuickTask.Active = true;
            QuickTask.AskBefore = chkAsk.Checked;
            QuickTask.Comment = "Created with QickTask on " + DateTime.Now.ToString();
            QuickTask.CreatedDate = DateTime.Now;
            QuickTask.LastModified = DateTime.Now;
            QuickTask.FilePath = txtFilePath.Text;
            QuickTask.Message = txtMessage.Text;
            QuickTask.Hour = (int) numHour.Value;
            QuickTask.Minute = (int) numMinute.Value;
            QuickTask.Recurrence = Recurrences.Everyday;
            QuickTask.Timer = (int) numTimer.Value;
            QuickTask.Title = "Quick Task";

            quickTaskStarted = true;
            btnStartStop.Text = "&Stop";

            numHour.Enabled = numMinute.Enabled = cboActions.Enabled =
                txtFilePath.Enabled = btnOpenFile.Enabled = txtMessage.Enabled =
                chkAsk.Enabled = numTimer.Enabled = false;
        }

        private void mnuViewQuickActions_Click(object sender, EventArgs e)
        {
            mnuViewQuickActions.Checked = !mnuViewQuickActions.Checked;
            QuickWindow.Visible = mnuViewQuickActions.Checked;
            if (!mnuViewQuickActions.Checked)
                listTasks.Width += QuickWindow.Width+5;
            else
                listTasks.Width -= QuickWindow.Width+5;
        }

        private void mnuViewStatusbar_Click(object sender, EventArgs e)
        {
            mnuViewStatusbar.Checked = !mnuViewStatusbar.Checked;
            Statusbar.Visible = mnuViewStatusbar.Checked;
            if (!mnuViewStatusbar.Checked)
                listTasks.Height += Statusbar.Height;
            else
                listTasks.Height -= Statusbar.Height;
        }

        private void mnuViewDetails_Click(object sender, EventArgs e)
        {
            mnuViewDetails.Checked = btnViewDetails.Checked = true;
            mnuViewTiles.Checked = mnuViewLargeIcon.Checked = btnViewLarge.Checked = btnViewTiles.Checked = false;
            listTasks.View = View.Details;
        }

        private void mnuViewLargeIcon_Click(object sender, EventArgs e)
        {
            mnuViewLargeIcon.Checked = btnViewLarge.Checked = true;
            mnuViewDetails.Checked = mnuViewTiles.Checked = btnViewDetails.Checked = btnViewTiles.Checked = false;
            listTasks.View = View.LargeIcon;
        }

        private void mnuViewTiles_Click(object sender, EventArgs e)
        {
            mnuViewTiles.Checked = btnViewTiles.Checked = true;
            mnuViewDetails.Checked = mnuViewLargeIcon.Checked = btnViewDetails.Checked = btnViewLarge.Checked = false;
            listTasks.View = View.Tile;
        }

        private void mnuViewToolbar_Click(object sender, EventArgs e)
        {
            mnuViewToolbar.Checked = !mnuViewToolbar.Checked;
            Toolbars.Visible = mnuViewToolbar.Checked;
            if (!mnuViewToolbar.Checked)
            {
                listTasks.Top -= Toolbars.Height;
                listTasks.Height += Toolbars.Height;
            }
            else
            {
                listTasks.Top += Toolbars.Height;
                listTasks.Height -= Toolbars.Height;
            }
        }

        private void mnuDoShutdown_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Do you realy want to Shutdown your computer now?", "Shutdown",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.PowerOff();
            }
        }

        private void mnuDoReboot_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you realy want to Reboot your computer now?", "Reboot",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.Reboot();
            }
        }

        private void mnuDoLogoff_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you realy want to Logoff from your computer now?", "Logoff",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.PowerOff();
            }
        }

        private void mnuDoStandby_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you realy want to Standby your computer now?", "Standby",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.Standby();
            }
        }

        private void mnuDoHibernate_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you realy want to Hibernate your computer now?", "Hibernate",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.Hibernate();
            }
        }

        private void mnuDoLock_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you realy want to Lock your computer now?", "Lock",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SystemActions.Lock();
            }
        }

        private void mnuViewSettings_Click(object sender, EventArgs e)
        {
            new SettingForm().ShowDialog();
        }

    }
}
